import os
from io import BytesIO

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium import webdriver
from selenium.webdriver import ActionChains
from day05_0214_captcha_1kkk.compare_helper import *

# 打开浏览器
BROWSER = webdriver.Chrome()
BROWSER.set_window_size(1600, 900)
# 隐式等待
WAIT = WebDriverWait(BROWSER, 5)
IMG_PATH = './images'

SUCCEED = True


def get_page(url):
    """获取网页"""

    BROWSER.get(url)
    pre_action()  # 预操作

    # 获取输入框
    input_el = WAIT.until(ec.presence_of_element_located((By.CSS_SELECTOR, 'input[type="text"]')))
    input_el.clear()

    result_list = break_captcha()

    while not SUCCEED:
        result_list = redo(input_el)

    js_str0 = f'document.getElementsByClassName("rotate-background")[0].children[0].value={result_list[0]};'
    js_str1 = f'document.getElementsByClassName("rotate-background")[1].children[0].value={result_list[1]};'
    js_str2 = f'document.getElementsByClassName("rotate-background")[2].children[0].value={result_list[2]};'
    js_str3 = f'document.getElementsByClassName("rotate-background")[3].children[0].value={result_list[3]};'

    BROWSER.execute_script(js_str0 + js_str1 + js_str2 + js_str3)

    # FIXME 注意：跑的时候将此处替换成自己的账号密码！！！
    input_el.send_keys('账号\t密码\n')


def break_captcha():
    """破解验证码"""

    global SUCCEED
    result_list = []

    cut_list = get_crop()  # 获取截图
    for cut in cut_list:
        result = match_img(cut)
        if result:
            result_list.append(result)
        else:
            print('失败')
            SUCCEED = False
            return
    else:
        SUCCEED = True
        return result_list


def pre_action():
    """预操作"""

    # 打开登录界面
    login_el = BROWSER.find_element_by_class_name('header-avatar')
    # print(login_el.get_attribute('outerHTML'))
    ActionChains(BROWSER).move_to_element(login_el).perform()
    ActionChains(BROWSER).click().perform()
    # 点击同意按钮 (这个破节点是真的难取)
    agree_el = BROWSER.find_element_by_css_selector(
        'a[style="float: left;display: inline-block;width: 50%;height: 60px;line-height: 60px;'
        'font-size: 18px;background-color: #E33535;color: #fff;'
        'text-align: center;text-decoration: none;"]')
    agree_el.click()


def get_big_image():
    """取浏览器窗口内全图"""

    BROWSER.execute_script('window.scrollTo(0, 0)')
    screenshot = BROWSER.get_screenshot_as_png()
    screenshot = Image.open(BytesIO(screenshot))
    return screenshot


def get_crop():
    """获取四张截图"""

    screenshot = get_big_image()

    # 获取下图坐标
    img = WAIT.until(ec.presence_of_element_located((By.CSS_SELECTOR, '.rotate-background')))
    loc = img.location

    # 截图
    crop_image1 = screenshot.crop((loc['x'], loc['y'], loc['x'] + 76, loc['y'] + 76))
    crop_image2 = screenshot.crop((loc['x'] + 78, loc['y'], loc['x'] + 154, loc['y'] + 76))
    crop_image3 = screenshot.crop((loc['x'] + 156, loc['y'], loc['x'] + 232, loc['y'] + 76))
    crop_image4 = screenshot.crop((loc['x'] + 234, loc['y'], loc['x'] + 310, loc['y'] + 76))

    return [crop_image1, crop_image2, crop_image3, crop_image4]


def match_img(cut):
    """匹配截图"""

    global SUCCEED

    for img in os.listdir(IMG_PATH):
        standard = Image.open(os.path.join(IMG_PATH, img))
        similar_level = get_compare(cut, standard)
        if similar_level >= 85:
            return img[1]
    else:
        return None


def redo(input_el):
    """重来"""

    input_el.send_keys('gg\tgg\n')
    result_list = break_captcha()
    return result_list


def main2():
    """主函数"""

    url = 'http://www.1kkk.com/'
    get_page(url)


if __name__ == '__main__':
    main2()
